// src/sql/executor/mod.rs

mod schema;
mod mutation;
mod query;

use crate::error::Result;
use crate::sql::engine::Transaction;
use crate::sql::executor::mutation::Insert;
use crate::sql::executor::query::Scan;
use crate::sql::executor::schema::CreateTable;
use crate::sql::plan::Node;
use crate::sql::types::Row;

// 执行器接口
pub trait Executor<T: Transaction> {
    fn execute(self: Box<Self>, txn: &mut T) -> Result<ResultSet>;
}

// 当具体类型在编译期无法确定时使用dyn 动态分配空间
impl<T: Transaction> dyn Executor<T> {
    // Trait 对象 dyn Executor 是动态大小类型，编译器无法预知具体类型的内存大小
    // 用 Box 作为智能指针, 将 trait 对象存储在堆上，指针本身有固定大小
    pub fn build(node: Node) -> Box<dyn Executor<T>> {
        match node {
            Node::CreateTable { schema } => CreateTable::new(schema),
            Node::Insert { table_name, columns, values }
            => Insert::new(table_name, columns, values),
            Node::Scan { table_name } => Scan::new(table_name)
        }
    }
}

// 执行结果集
#[derive(Debug)]
pub enum ResultSet {
    CreateTable {
        table_name: String,
    },
    Insert {
        count: usize,
    },
    Scan {
        columns: Vec<String>,
        rows: Vec<Row>,
    },
}

